import { createServer } from 'node:http';
import { WebSocketServer, createWebSocketStream } from 'ws';
import { getRequestTunnelClientId, getTunnelClientId, HEADERCLIENTID } from './utils.js';
import { MessageObserver } from 'requester-utils/be/protocol.js';

const port = 8081;

const server = createServer((req, res) => {
    let clientId = getRequestTunnelClientId(req);
    if (clientId && clients.has(clientId)) {
        let headers = {};
        Reflect.ownKeys(req.headers).forEach(a => {
            if (a !== HEADERCLIENTID) {
                headers[a] = req.headers[a];
            }
        });
        clients.get(clientId).publish('request', {
            url: req.url,
            method: req.method,
            headers,
            body: req
        }).then(({ status, headers, stream }) => {
            res.writeHead(status, headers);
            stream.pipe(res);
        });
    } else {
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
            code: 1,
            msg: 'no tunnel tag'
        }));
    }
});
const clients = new Map();
const wss = new WebSocketServer({ server });
wss.on('connection', (ws, req) => {
    let clientId = getTunnelClientId(req);
    console.log('==>', clientId);
    if (clientId) {
        const duplex = createWebSocketStream(ws);
        let observer = MessageObserver.form({ readable: duplex, writable: duplex });
        clients.set(clientId, observer);
    }
    ws.on('error', console.error);
});
server.on('error', e => console.log(e));
server.listen(port, () => {
    console.log('listen:', port);
});